package com.demo;

import com.mysql.jdbc.Driver;

import java.sql.*;

public class Test {
    public static void main(String[] args){
        System.out.println("test");
//        test1();
//        test2();
        test3();
    }

    /**
     * 查询数据
     */
    public static void test1(){
        try {
            //        1. 注册驱动
//            DriverManager.registerDriver(new Driver());
            Class.forName("com.mysql.jdbc.Driver");
            //        2. 获取连接  url  uri
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo2", "root", "123456");
            //        3. 创建发送sql语句的对象
            Statement statement = conn.createStatement();
            //4. 发送sql 执行sql 斌返回结果
            String sql = "select * from emp";
            ResultSet resultSet = statement.executeQuery(sql);
            //5. 结果集的解析
            while (resultSet.next()){
//                int id = resultSet.getInt("id");
                int id = resultSet.getInt(1);
                String name = resultSet.getString("name");
                String job = resultSet.getString("job");
                System.out.println("id是："+id +"\t名字："+name+"\t工作："+job);
            }
            //6. 释放资源  先开的后关
            resultSet.close();
            statement.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入数据
     */
    public static void test2(){
        // 在MySQL8.0以上 可以不注册驱动
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo2", "root", "123456");
            Statement statement = conn.createStatement();
//            22	tom22	22	程序员	10000	2023-11-24	2	2
            String sql = "insert into emp values (24,'李好',18,'sale',8000,'2023-11-30',1,4)";
            int index = statement.executeUpdate(sql);
            System.out.println("执行插入的结果：" + index);
            statement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除数据
     */
    public static void test3(){
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo2", "root", "123456");
            Statement statement = conn.createStatement();
            String sql = "delete from emp where id=23 or id=24";
            int index = statement.executeUpdate(sql);
            System.out.println("执行删除的结果：" + index);
            statement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
